﻿using System.Collections.Generic;
using KLS.PPDS.Core.Entity;
using KLS.PPDS.Data.Database.Repository.RepositoryInterfaces;
using System.Linq;


namespace KLS.PPDS.Data.Database.Repository.EntityRepository
{
    public class UserRepository: LinqRepository<User>, IUserRepository
    {
//        public IEnumerable<User> GetByCompanyId(int companyId)
//        {
//            var session = NHibernateHelper.GetCurrentSession();
//            string query = string.Format(@"from user u where u.Groups.Count>0 and u.Groups[0].Group.CompanyId=:cid                           
//                                order by u.UserName asc"
//                           );
//            IEnumerable<User> userList = session.CreateQuery(query).SetParameter("cid", companyId).Enumerable<User>();
//            return userList;
//        }

         public List<User> GetAll()
         {
            // var x = FindAll().ToList().Where(c => c.IsDeleted.Equals(false) && c.CompanyId.HasValue==false).ToList();

             return FindAll().ToList().Where(u => u.IsDeleted.Equals(false) && u.Company != null && u.Company.IsDeleted.Equals(false)).Union(FindAll().ToList().Where(c => c.CompanyId == null && c.IsDeleted.Equals(false))).OrderBy(c => c.UserName).ToList();
         }


         public IList<User> GetAllUserByComapnyId(int companyId)
         {

             return FindAll().ToList().Where(u => u.IsDeleted.Equals(false) && u.CompanyId == companyId && u.Company.IsDeleted.Equals(false)).OrderBy(c => c.UserName).ToList();
             
         }

        public User GetUserByName(string name)
        {
            return FindAll().ToList().Where(c =>  c.UserName.ToLower().Equals(name.ToLower())).FirstOrDefault();
        }

        #region IUserRepository Members
        
        /// <summary>
        /// Get User By Role Name
        /// </summary>
        /// <param name="roleName"></param>
        /// <returns></returns>
         public IList<User> GetUserByRoleName(string roleName, int? companyId)
         {

             

            string sql1 = @"
            SELECT     [User].*
            FROM         [User] INNER JOIN
            Role ON [User].RoleId = [Role].RoleId
            where [User].IsDeleted = 0 ";

            if (companyId.HasValue && companyId>0)
            {
                sql1 += " and [User].CompanyId = " + companyId  ;
            }

            if (!string.IsNullOrEmpty(roleName))
            {
                sql1 += " AND [Role].RoleName='" + roleName + "' ";
            }

            sql1 += " order by [User].UserName ";

            var query =   Session.CreateSQLQuery(sql1).AddEntity(typeof(User));

            return query.List<User>();
         }

         #endregion

    }
}
